package br.gfca.lanhostfinder;

public class ExternalAppController implements Runnable {

	private boolean[] foundHosts;
	private String appCommand;
	private int pollTime;
	private Process appProcess;
	
	public ExternalAppController( boolean[] foundHosts, String appCommand, int pollTime ) {
		this.foundHosts = foundHosts;
		this.appCommand = appCommand;
		this.pollTime = pollTime;
	}
	
	@Override
	public void run() {
		try {
			while( true ) {
				if( this.shouldRunApp() ) {
					if( this.appProcess == null) {
						this.appProcess = Runtime.getRuntime().exec(this.appCommand);
					}
				}
				else {
					if( this.appProcess != null) {
						this.appProcess.destroy();
						this.appProcess = null;
					}
				}
				Thread.sleep(pollTime * 1000);
			}
		}
		catch (Exception e) {
			System.out.println("==== External App Controller terminated ====");
			e.printStackTrace();
			System.exit(0);
		}
	}
	
	private boolean shouldRunApp() {
		int count = 0;
		for( boolean b : foundHosts ) {
			count = b ? count + 1 : count;
		}
		
		boolean b = count <= 2;
		
		System.out.println((b ? "Start" : "Stop") + " external application.");
		return b;
	}
}